﻿//https://leetcode.cn/problems/binary-tree-maximum-path-sum/?envType=study-plan-v2&envId=top-100-liked

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    int maxSum = INT_MIN;
public:
    int maxPathSum(TreeNode* root)
    {
        GetMaxSum(root);
        return maxSum;
    }

    int GetMaxSum(TreeNode* root)
    {
        if (root == nullptr)
        {
            return 0;
        }

        //计算左右子树的路径最大和
        int leftmax = max(GetMaxSum(root->left), 0);
        int rightmax = max(GetMaxSum(root->right), 0);

        //计算整个路径的节点最大值
        int newpath = root->val + leftmax + rightmax;

        //更新最大值
        maxSum = max(maxSum, newpath);

        return root->val + max(leftmax, rightmax);
    }
};